home *** CD-ROM | disk | FTP | other *** search
/ NetNews Offline 2 / NetNews Offline Volume 2.iso / news / comp / lang / c++-part1 / 4703 < prev    next >
Encoding:
Text File  |  1996-08-06  |  1.6 KB  |  65 lines

  1. Path: news.ios.com!usenet
  2. From: leonardj@tribeca.ios.com (John Leonard)
  3. Newsgroups: comp.lang.c++
  4. Subject: Aborting Constructors, Part II
  5. Date: Wed, 31 Jan 1996 19:09:25 GMT
  6. Organization: Internet Online Services
  7. Message-ID: <4eoeck$t6n@news.ios.com>
  8. NNTP-Posting-Host: ppp-47.ts-7.hck.idt.net
  9. X-Newsreader: Forte Free Agent 1.0.82
  10.  
  11.  
  12.     Earlier, I posted a message about aborting a constructor if for some
  13. reason some resource cannot be allocated. I did some thinking about
  14. the problem and I thought, why couldn't you just call 'delete' inside
  15. of the constructor itself and then let the destructor take care of the
  16. release of all resources allocated so far. To find out whether or not
  17. this would work, I wrote the following test program, compiled and ran
  18. it under BC++ 4.52. It produced the output at the bottom of the page:
  19.  
  20. //        File:        abort constructor test
  21.  
  22. #include    <iostream.h>
  23. #include    <except.h>
  24. #include    <cstring.h>
  25.  
  26. class        test{
  27.     public:
  28.         test();
  29.         ~test();
  30. };
  31.  
  32. test::test(){
  33.     cout << "constructing object\n";
  34.     delete this;
  35.     throw(xmsg(string("deleted the object!\n")));
  36. }
  37.  
  38. test::~test(){
  39.     cout << "deleting object\n";
  40. }
  41.  
  42. void    main(){
  43.  
  44.     try{
  45.         test *at = new test;
  46.     }
  47.  
  48.     catch(xmsg error){
  49.         cout << error.why();
  50.     }
  51. }
  52.  
  53.     When compiled and run this produces the following output:
  54.  
  55. constructing object
  56. deleting object
  57. deleted the object!
  58.  
  59.     I'm guessing from this result that this is a valid way to do this. If
  60. you have any opinion on this, especially if you happen to know of a
  61. reason why this is not good, or conflicts somehow with what is
  62. considered good C++ programming practice, I would like to know.
  63.     Thanks
  64.  
  65.